package org.judking.CarKeeper.command;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.judking.CarKeeper.service.ResourceService;

import android.util.Log;

public class PddObdCommandHelper {

	public static Map<String, BaseObdCommand> genMapFromFile(InputStream in) {
		HashMap<String, BaseObdCommand> commands = new HashMap<String, BaseObdCommand>();
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String line;
		try {
			while ((line = br.readLine()) != null) {
				PddObdCommand cmd = genPDDCmd(line);
				commands.put(cmd.getPID(), cmd);
			}
			return commands;
		} catch (IOException e) {
			Log.i("judking",
					"PDDObdCommandHelper: genListFromFile io exception: " + e);
		}
		return null;
	}

	/**
	 * ¸ù¾ÝÅäÖÃÐÅÏ¢£¬Éú³ÉÒ»¸öPDDObdCommand¶ÔÏó ÅäÖÃÐÅÏ¢¸ñÊ½ÈçÏÂ£º name PID
	 * unit4Measure [zoomRatio] [translationVal]
	 * 
	 * @param info
	 *            ÅäÖÃÎÄ¼þÖÐÒ»ÐÐÐÅÏ¢
	 * @return
	 */
	private static PddObdCommand genPDDCmd(String info) {
		String[] fields = splitCfgLine(info);
		PddObdCommand command;

		if (fields.length == 6) {
			command = new PddObdCommand(fields[1], Double.valueOf(fields[3]),
					Double.valueOf(fields[4]), Integer.parseInt(fields[5]));
		} else if (fields.length == 4) {
			command = new PddObdCommand(fields[1], Integer.parseInt(fields[3]));
		} else {
			throw new RuntimeException(
					"judking: PDDObdCommandHelper.genPDDCmd: pdd config profile format incorrect: "
							+ info);
		}

		command.setName(fields[0]);
		command.setUnit4Measure(fields[2]);

		return command;
	}

	private static String[] splitCfgLine(String info) {
		info = info.trim();
		info = info.replaceAll("(\t){2,}", "\t");
		return info.split("\t");
	}

	/**
	 * Í¨¹ý0100£¬0120µÈÃüÁî»ñÈ¡Æû³µÖ§³ÖµÄPIDÖµ£¬²¢Éú³É¶ÔÓ¦µÄÃüÁîÁÐ±í
	 * 
	 * @param cmdRtn
	 *            ³¤¶ÈÎª8Î»µÄ±íÊ¾16½øÖÆµÄ×Ö·û´®, Ã¿Á½Î»´ú±íÒ»×Ö½Ú
	 * @param base
	 *            »ùÊý¡£¶ÔÓÚ0120ÃüÁî£¬»ùÊýÎª0x20
	 * @param ctn
	 *            ÊÇ·ñ¼ÌÐøÍùºó¶ÁÈ¡PIDÁÐ±í
	 * @return
	 */
	public static List<BaseObdCommand> genListFromLightTower(String cmdRtn,
			int base, boolean[] ctn) {
		if (cmdRtn == null || cmdRtn.length() > 8) {
			Log.e("judking", "genListFromCmdRtn: cmdRtn不能为空且长度应小于等于8" + cmdRtn);
			return null;
		}
		Map<String, BaseObdCommand> cmdMap = genMapFromFile(ResourceService
				.getFromAssets("PDDObdCmdConfig.txt"));
		long tmp = Long.parseLong(cmdRtn, 16);
		String binaryFmt = String.format("%32s", Long.toBinaryString(tmp));
		binaryFmt = binaryFmt.replace(' ', '0');
		List<BaseObdCommand> commands = new ArrayList<BaseObdCommand>();
		for (int i = 0; i < 32; ++i) {
			if (binaryFmt.charAt(i) == '1') {
				int pid = base + i + 1;
				String strPid = Integer.toHexString(pid);
				strPid = String.format("%2s", strPid).replace(' ', '0');

				if (i != 31) {
					BaseObdCommand tmpCmd = cmdMap.get(strPid.toLowerCase());
					tmpCmd = tmpCmd == null ? cmdMap.get(strPid.toUpperCase())
							: tmpCmd;
					if (tmpCmd == null) {
						//commands.add(new AsleepObdCommand("01", strPid));
					} else {
						commands.add(tmpCmd);
					}
				}
			}
		}
		ctn[0] = binaryFmt.charAt(31) == '1' ? true : false;
		return commands;
	}
}